/*
 *接口编写处...
*如果接口需要做Action的权限验证，请在Action上使用属性
*如: [ApiActionPermission("materialfactorycost",Enums.ActionPermissionOptions.Search)]
 */
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Http;
using ATkg.BizAppProject.DomainModels;
using ATkg.BizAppProject.IServices;
using Microsoft.AspNetCore.Authorization;
using System.Globalization;
using Microsoft.AspNetCore.Components.Forms;
using SqlSugar;
using DGZImp.Core.Extensions;

namespace ATkg.BizAppProject.Controllers
{
    public partial class materialfactorycostController
    {
        private readonly ImaterialfactorycostService _service;//访问业务代码
        private readonly IHttpContextAccessor _httpContextAccessor;

        [ActivatorUtilitiesConstructor]
        public materialfactorycostController(
            ImaterialfactorycostService service,
            IHttpContextAccessor httpContextAccessor
        )
        : base(service)
        {
            _service = service;
            _httpContextAccessor = httpContextAccessor;
        }

        [HttpGet("GetMaterialPro")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<JsonResult> GetMaterialPro(string datalevel,string start_data, string end_data)
        //public async Task<JsonResult> SyncProductionTask_wgjy([FromBody] PageDataOptions order_no_)

        {
            Console.WriteLine("get方法调用");
            Console.WriteLine(datalevel);
            Console.WriteLine(start_data);
            Console.WriteLine(end_data);
            var r = await Service.GetMaterialProMes(start_data, end_data);

            return JsonNormal(r);
        }

        [HttpPost("SyncProductionTask_Getname")]
        [AllowAnonymous]
        public async Task<JsonResult> SyncProductionTask_Getname()
        {



            var r = await Service.Syncname_cai();
            return JsonNormal(r);
        }


        [HttpGet("get_db_eng")]
        [AllowAnonymous]
        //[HttpBody]
        public async Task<JsonResult> get_db_eng(string datalevel, string start_data)
        //public async Task<JsonResult> SyncProductionTask_wgjy([FromBody] PageDataOptions order_no_)

        {
            Console.WriteLine("get方法调用");
            //List<string> result = GetLastAndCurrentMonth24th(start_data);
            //Console.WriteLine(result);  // 输出：2025-05-24 至 2025-06-24
            ////string aa = result[0].ToString()
            //Console.WriteLine(result[0]);  // 输出：2025-05-24 至 2025-06-24
            //object r = null;
            //Console.WriteLine(result[1]);  // 输出：2025-05-24 至 2025-06-24
            double total_en_data = 0;
            if (datalevel == "月度")
            {
                string dateString = start_data;
                List<string> result = GetLastAndCurrentMonth24th(start_data);
                char[] separators = { '-' };
                string startTime = result[0] + " " + "00:00:00";
                string endtime = result[0] + " " + "00:30:00";
                List<object> r_first = (List<object>)await Service.get_db_get_db_eng(startTime, endtime);
                string startTime_final = result[1] + " " + "00:00:00";
                string endtime_final = result[1] + " " + "00:30:00";
                List<object> r_final = (List<object>)await Service.get_db_get_db_eng(startTime_final, endtime_final);
                double first_en_data = 0;
                for(int i = 0; i < r_first.Count; i++)
                {
                    //Console.WriteLine($"{r_first[i]["region_name"]}, 当月24号：{result[1]:yyyy-MM-dd}")
                    Dictionary<string, string> region_name = (Dictionary<string,string>)r_first[i];
                    //Console.WriteLine(region_name["region_name"]);
                    first_en_data += Double.Parse(region_name["vriable_value_now"]);
                }
                double current_en_data = 0;
                for (int i = 0; i < r_final.Count; i++)
                {
                    //Console.WriteLine($"{r_first[i]["region_name"]}, 当月24号：{result[1]:yyyy-MM-dd}")
                    Dictionary<string, string> region_name = (Dictionary<string, string>)r_final[i];
                    //Console.WriteLine(region_name["region_name"]);
                    current_en_data += Double.Parse(region_name["vriable_value_now"]);
                }
                total_en_data = current_en_data - first_en_data;
                Console.WriteLine(r_first.Count);
            }
            else
            {
                string startTime = start_data + " "+"00:00:00";
                string endtime = start_data + " " + "00:30:00";
                List<object> r_first = (List<object>)await Service.get_db_get_db_eng(startTime, endtime);
                string startTime_final = start_data + " " + "23:00:00";
                string endtime_final = start_data + " " + "23:30:00";
                List<object> r_final = (List<object>)await Service.get_db_get_db_eng(startTime_final, endtime_final);
                double first_en_data = 0;
                for (int i = 0; i < r_first.Count; i++)
                {
                    //Console.WriteLine($"{r_first[i]["region_name"]}, 当月24号：{result[1]:yyyy-MM-dd}")
                    Dictionary<string, string> region_name = (Dictionary<string, string>)r_first[i];
                    //Console.WriteLine(region_name["region_name"]);
                    first_en_data += Double.Parse(region_name["vriable_value_now"]);
                }
                double current_en_data = 0;
                for (int i = 0; i < r_final.Count; i++)
                {
                    //Console.WriteLine($"{r_first[i]["region_name"]}, 当月24号：{result[1]:yyyy-MM-dd}")
                    Dictionary<string, string> region_name = (Dictionary<string, string>)r_final[i];
                    //Console.WriteLine(region_name["region_name"]);
                    current_en_data += Double.Parse(region_name["vriable_value_now"]);
                }
                total_en_data = current_en_data - first_en_data;
            }
            var r = new List<double>();
            r.Add(total_en_data);

            return JsonNormal(r);
        }

        public static List<string> GetLastAndCurrentMonth24th(string dateString)
        {
            // 解析输入日期（验证格式有效性）
            if (!DateTime.TryParseExact(dateString, "yyyy-MM-dd", CultureInfo.InvariantCulture,
                                       DateTimeStyles.None, out DateTime currentDate))
            {
                throw new ArgumentException("输入日期格式无效，需为yyyy-MM-dd");
            }

            // 计算当月24号（时间部分为00:00:00）
            DateTime currentMonth24th = new DateTime(currentDate.Year, currentDate.Month, 24);

            // 计算上月24号（处理跨年场景）
            int lastMonth = currentDate.Month == 1 ? 12 : currentDate.Month - 1;
            int lastYear = currentDate.Month == 1 ? currentDate.Year - 1 : currentDate.Year;
            DateTime lastMonth24th = new DateTime(lastYear, lastMonth, 24);

            // 格式化为无时间字符串并返回
            return new List<string>
        {
            lastMonth24th.ToString("yyyy-MM-dd"),
            currentMonth24th.ToString("yyyy-MM-dd")
        };
        }
        

     }
}
